package com.abe.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import android.content.Context;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

public class DataCacheUtil {
	
	/**
	 * 通过result生成缓存文件
	 * 
	 * @param fileUrl
	 * @param resule
	 * @return
	 */
	public boolean create(String fileUrl, String resule) {
		try {
			String temp = resule;
			BASE64Encoder base64en = new BASE64Encoder();
			String tempjiami = base64en.encode(temp.getBytes("UTF-8"));
			File file = new File(fileUrl);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(fileUrl);
			fw.write(tempjiami, 0, tempjiami.length());
			fw.flush();
			fw.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 删除缓存文件
	 * @param fileURL
	 */
	public void deleteXML(String fileURL){
		File file = new File(fileURL);
		if (file.exists()) {
			file.delete();
		}
	}
	/**
	 * 读取文件中的内容按照字符读取
	 * @param fileURL
	 */
	public String readFileByChars(String fileURL) {
		StringBuffer result = new StringBuffer();
		StringBuffer tempResult = new StringBuffer();
        Reader reader = null;
        try {
            char[] tempchars = new char[10];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileURL));
            // 读入多个字符到字符数组中，charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
                	tempResult.append(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                        	tempResult.append(tempchars[i]);
                        }
                    }
                }
            }
            BASE64Decoder base64De = new BASE64Decoder();
            result.append(new String(base64De.decodeBuffer(tempResult.toString()), "UTF-8" ));
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return result.toString();
    }
	
	
	/**
	 * 获取可用的缓存目录
	 * @param context
	 * @param filename
	 * @return
	 */
	public static String getCacheDir(Context context,String filename){
		String fileURL = null;
		if (context.getExternalCacheDir() != null) {
			fileURL = context.getExternalCacheDir().toString()+"/"+ filename;
		} else {
			fileURL =  context.getCacheDir().toString() + "/"+ filename;
		}
		return fileURL;
	}
}
